const express = require('express')

const router = express.Router()

const db = require('../database/index')

const utility = require('utility')
// 根据token 获取用户信息
router.get('/userinfo', (req, res) => {
    let sql = `select * from user where id=${req.user.id}`

    db(sql, (err, results) => {
        if (err) {
            throw err
        }
        res.send({ status: 0, message: '获取用户信息成功！' })

    })
})
// 根据id修改用户信息 
router.post('/userinfo', (req, res) => {
    let { id, nickname, email } = req.body
    let sql = `update user set nickname="${nickname}",email="${email}" where id=${id} `

    db(sql, (err, results) => {
        if (err) {
            throw err
        }
        res.send({ status: 0, message: '修改用户信息成功！' })

    })

})
// 重置密码 新旧密码都需要加密 根据id去分别服务两个密码
router.post('/updatepwd', (req, res) => {

    let { oldPwd, newPwd } = req.body
    oldPwd = utility.md5(oldPwd)
    newPwd = utility.md5(newPwd)
    // 数据操作
    let sql = `select * from user where id=${req.user.id} and password="${oldPwd}" `
    db(sql, (err, results) => {
        if (err) {
            throw err
        }
        // 验证了用户的旧密码
        if (results.length === 0) {
            return res.send({
                status: 1,
                message: '旧密码错误！'
            })
        }
        // 查询到开始重置密码
        let sql = `update user set password="${newPwd}" where id=${req.user.id}`
        db(sql, (err, results) => {
            if (err) {
                throw err
            }
            if (results.affectedRows !== 1) {
                return res.send({
                    status: 1,
                    message: '修改密码失败！'
                })
            }
            res.send({ status: 0, message: '更新密码成功！' })
        })
    })

})
// 跟换用户头像
router.post('/update/avatar',(req,res)=>{
    let sql=`update user set user_pic="${req.body.avatar}" where id=${req.user.id}`
    db(sql,(err,results)=>{
        if (err) {
            throw err
        }
        if (results.affectedRows !== 1) {
            return res.send({status:1,message:'跟换头像失败！'})
        }
    })


    res.send({status:0,message:'更换头像成功！'})
})

module.exports = router